package com.ctg.behavior.calc.impala.transfer.usergroups;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.ctg.behavior.calc.common.CtSQLParam;
import com.ctg.behavior.calc.impala.CtSQLTransfer;
import com.ctg.behavior.calc.impala.builder.CtCalcRestrictMeasureReportBuilder;
import com.ctg.behavior.calc.impala.report.CtCalcRestrictMeasureReport;
import com.ctg.behavior.calc.impala.report.uesrgroups.CtUGUBBehaviorReport;
import com.ctg.behavior.calc.utils.CtCalcSQLUtils;
import com.ctg.behavior.common.calc.CtCalc;
import com.ctg.behavior.common.calc.CtCalcRestrictMeasure;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class CtUGUBBehaviorTransfer implements CtSQLTransfer {

	@Autowired
	private CtUGUBMeasureTransfer ubMeasureTransfer;
	@Autowired
	private CtCalcRestrictMeasureReportBuilder restrictMeasureReportBuilder;

	/******************************************************
	 * @apiNote:
	 */
	@Override
	public String doTransfer(CtCalc calcObject, CtSQLParam sqlParam) {
		if (!(calcObject instanceof CtUGUBBehaviorReport)) {
			log.warn("calcObject is not CtUGUserBehaviorReport, class={}", calcObject.getClass());
			log.warn("calcObject: {}", JSON.toJSON(calcObject));
			return "";
		}
		CtUGUBBehaviorReport ubBehavior = (CtUGUBBehaviorReport) calcObject;
		log.info("CalcBody={}", JSON.toJSONString(ubBehavior));

		String measuresRelation = ubBehavior.getRelation();
		StringBuilder impalaSQL = new StringBuilder();
		impalaSQL.append(" ( ");
		List<CtCalcRestrictMeasure> measures = ubBehavior.getMeasures();
		for (int measuresIndex = 0; measuresIndex < measures.size(); measuresIndex++) {
			CtCalcRestrictMeasure oneMeasure = measures.get(measuresIndex);
			// 把Behavior中的measures数组中的一个measure对象转换为SQL条件
			CtCalcRestrictMeasureReport restrictMeasureReport = null;
			restrictMeasureReport = restrictMeasureReportBuilder.doBuilder(oneMeasure, ubBehavior.getAppId());
			String sqlMeasure = ubMeasureTransfer.doTransfer(restrictMeasureReport, CtSQLParam.createParam());
			// impalaSQL.append(" device_id IN ( ");
			// 增加别名
			String userIdWithAlias = CtCalcSQLUtils.fillAlias("user_id", sqlParam);
			impalaSQL.append(" ").append(userIdWithAlias).append(" IN ( ");
			impalaSQL.append(sqlMeasure);
			impalaSQL.append(" ) ");
			if (measuresIndex < measures.size() - 1) {
				impalaSQL.append(measuresRelation.toUpperCase()).append(" ");
			}
		}
		impalaSQL.append(" ) ");

		String retSQL = impalaSQL.toString();
		log.info("CalcSQL={}", impalaSQL);

		return retSQL;
	}

}
